﻿using MhAdmin.Application.Services.CMD.MasterDataGroup.Dto;
using MhAdmin.SqlSugar.Extension;
using MhAdmin.System.Entity.CMD;

namespace MhAdmin.Application.Services.CMD.MasterDataGroup
{
	public class MasterDataGroupService : DbRepository<SysMasterDataGroup>, IMasterDataGroupService
	{
		private readonly ISimpleCacheService simpleCacheService;
		private readonly ISysOrgService sysOrgService;

		public MasterDataGroupService(ISimpleCacheService simpleCacheService, ISysOrgService sysOrgService)
		{
			this.simpleCacheService = simpleCacheService;
			this.sysOrgService = sysOrgService;
		}

		/// <inheritdoc />
		public async Task Add(MasterDataGroupAddInput input, string name = MhAdminConst.MasterDatagroup)
		{
			await CheckInput(input, name);//检查参数
			var sysMasterDataGroup = input.Adapt<SysMasterDataGroup>();//实体转换
			sysMasterDataGroup.Code = RandomHelper.CreateRandomString(10);//赋值Code
			if (await InsertAsync(sysMasterDataGroup))//插入数据
				await RefreshCache();//刷新缓存
		}

		/// <inheritdoc/>
		public async Task<SqlSugarPagedList<SysMasterDataGroup>> Page(MasterDataGroupPageInput input)
		{
			ISugarQueryable<SysMasterDataGroup> query = Context.Queryable<SysMasterDataGroup>()
				.WhereIF(!string.IsNullOrEmpty(input.Code), it => it.Code.Contains(input.Code))//根据编码查询
				.WhereIF(!string.IsNullOrEmpty(input.SearchKey), it => it.Name.Contains(input.SearchKey))//根据名称查询
				.WhereIF(!string.IsNullOrEmpty(input.Type.ToString()), it => it.Type == input.Type.ToString())//根据类型查询
			.OrderByIF(!string.IsNullOrEmpty(input.SortField), $"{input.SortField} {input.SortOrder}")
			.OrderByDescending(it => it.CreateTime);//排序
			SqlSugarPagedList<SysMasterDataGroup> pageInfo = await query.ToPagedListAsync(input.Current, input.Size);//分页
			return pageInfo;
		}

		/// <inheritdoc />
		public async Task Edit(MasterDataGroupEditInput input, string name = MhAdminConst.MasterDatagroup)
		{
			await CheckInput(input, name);//检查参数
			var sysMasterDataGroup = input.Adapt<SysMasterDataGroup>();//实体转换
			if (await UpdateAsync(sysMasterDataGroup))//更新数据
				await RefreshCache();//刷新缓存
		}

		/// <inheritdoc />
		public async Task Delete(List<BaseIdInput> input, string name = MhAdminConst.MasterDatagroup)
		{
			//获取所有ID
			var ids = input.Select(it => it.Id).ToList();
			if (ids.Count > 0)
			{
				//删除主数据群组
				if (await Context.FalseDeleteChangeAsync<SysMasterDataGroup>(ids))
					await RefreshCache();//刷新缓存
			}
		}

		/// <inheritdoc />
		public override async Task<List<SysMasterDataGroup>> GetListAsync()
		{
			//先从Redis拿
			var sysMasterDataGroups = simpleCacheService.Get<List<SysMasterDataGroup>>(SystemConst.Cache_MasterDataGroup);
			if (sysMasterDataGroups == null)
			{
				//redis没有就去数据库拿
				sysMasterDataGroups = await base.GetListAsync();
				if (sysMasterDataGroups.Count > 0)
				{
					//插入Redis
					simpleCacheService.Set(SystemConst.Cache_MasterDataGroup, sysMasterDataGroups);
				}
			}
			return sysMasterDataGroups;
		}

		/// <inheritdoc />
		public async Task RefreshCache()
		{
			simpleCacheService.Remove(SystemConst.Cache_MasterDataGroup);//删除Key
			await GetListAsync();//重新写入缓存
		}


		#region 方法

		/// <summary>
		/// 检查输入参数
		/// </summary>
		/// <param name="sysMasterDataGroup">输入参数</param>
		/// <param name="name">名称</param>
		private async Task CheckInput(SysMasterDataGroup sysMasterDataGroup, string name)
		{
			//所有分类放一个列表
			var masterCategorys = new List<string>() { PartGroupType.Material.ToString(), PartGroupType.Product.ToString(), PartGroupType.Frock.ToString() };
			if (!masterCategorys.Contains(sysMasterDataGroup.Type))
				throw Oops.Bah($"{name}所属分类错误:{sysMasterDataGroup.Type}");
			List<SysMasterDataGroup> sysMasterDataGroups = await GetListAsync();//获取全部
			if (sysMasterDataGroups.Any(it => it.Code == sysMasterDataGroup.Code && it.Name == sysMasterDataGroup.Name && it.Id != sysMasterDataGroup.Id))//判断是否有名称重复的
				throw Oops.Bah($"存在重复的{name}:{sysMasterDataGroup.Name}");
			if (sysMasterDataGroup.Id > 0)//如果ID大于0表示编辑
			{
				var masterDataGroup = sysMasterDataGroups.Where(it => it.Id == sysMasterDataGroup.Id).FirstOrDefault();//获取当前主数据群组
				if (masterDataGroup == null)
				{
					throw Oops.Bah($"{name}不存在");
				}
			}
		}

		#endregion 方法
	}
}
